import axios from 'axios'

/**
 * util工具类 
 */
const utils = {
  vueObject: null,

  /**
   * @param {Vue} vueObject 
   * @description 创建utils实例，并且有netWork实例返回
   */
  init: function (vueObject) {
    this.vueObject = vueObject
  },

  /**
   * @param {Vue} vueObject 
   * @param {String} chartName 
   * @param {String}  args [2] 传入一个其他参数，用来设置其他接口
   * @returns {netWork}
   * @description 创建utils实例，并且有netWork实例返回
   */
  setConfig: function (vueObject, chartName) {
    this.vueObject = vueObject
    return new netWork(chartName, arguments[2])
  },

  /**
   * 
   * @param {List} doubleList_data 
   * @param {Object} value 
   * @returns 
   * @description 创建一个二维数组,默认值为value
   */
  createContainer_list(doubleList_data, value) {
    let dobuleList_cache = []
    doubleList_data.forEach((item, outer_index, obj) => {
      dobuleList_cache[outer_index] = []
      item.forEach((item, inner_index, obj) => {
        dobuleList_cache[outer_index][inner_index] = value
      })
    })
    return dobuleList_cache
  },

  /**
   * 
   * @param {String} chartName 
   * @param {String} API_name 
   * @returns {Promise}
   * @description 创建一个自定义API接口
   */
  createAPI_promise: function (chartName, API_name, obj_data) {
    return new Promise((resolve, reject) => {
      axios.post(`${chartName}/${API_name}`, obj_data).then(res => {
        if (res.data.success && utils.propertyHasValue_boolean(res.data, "rows")) {
          resolve(res)
        } else {
          reject(res)
        }
      })
    })
  },

  // 重构对象，用于发送更新信息请求（/updateNoNull）
  copyObject: function (object) {
    return JSON.parse(JSON.stringify(object))
  },

  /**
   * @param {*} res 请求的回调数据体
   * @param {String} message 展示的消息体
   * @param {Boolean} args 是否弹出显示消息-默认true
   * @returns {Boolean}
   */
  showMessage: function (res, message) {
    let isShow
    if (arguments[2] === false) {
      isShow = false
    } else {
      isShow = true
    }
    if (res.data.success === true) {
      if (isShow)
        this.vueObject.$message.success(`${message}成功`);
      return true
    } else {
      if (isShow)
        this.vueObject.$message.error(`${message}失败`);
      return false
    }
  },

  /**
   * @param {*} type 
   * @param {*} message 
   */
  notifyBr: function (type, message) {
    if (type === 'success') {
      this.vueObject.$notify({
        message: message,
        type: 'success',
        position: 'bottom-right',
        duration: 1500,
        offset: 5
      });
    } else if (type === 'error') {
      this.vueObject.$notify.error({
        message: message,
        position: 'bottom-right',
        duration: 1500,
        offset: 5
      });
    } else if (type === 'warning') {
      this.vueObject.$notify({
        message: message,
        type: 'warning',
        position: 'bottom-right',
        duration: 1500,
        offset: 5
      });
    } else if (type === 'info') {
      this.vueObject.$notify.info({
        message: message,
        position: 'bottom-right',
        duration: 1500,
        offset: 5
      });
    }
  },

  // 重置表单
  resetForm: function (formName) {
    this.vueObject.$refs[formName].resetFields();
  },

  //手机号正则校验
  checkMobile: function () {
    return (rule, value, cb) => {
      const regMobile =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法手机号"));
    };
  },

  //数组去重
  arrayUnique: function (arr) {
    return Array.from(new Set(arr));
  },

  // 消除字符串首尾的空格
  trim: function (str) {
    return str.replace(/(^\s*)|(\s*$)/g, '');
  },

  // 防止注入攻击
  checkData: function (v) {
    var temp = v;
    v = v.replace(/\\|\/|\.|\'|\"|\<|\>/g, function (str) {
      return '';
    });
    v = this.trim(v);
    var searchTap = v.length < temp.length ? false : true;
    if (!searchTap) {
      this.vueObject.$message.warning('请勿输入特殊字符或非法字符！');
    }
    return v;
  },

  /**
   *@returns {Object}
   *@description 获取登录者信息对象
   */
  getPersonInfo_Object: function () {
    let str_object = window.sessionStorage.getItem("userInfo");
    let obj_person = JSON.parse(str_object);
    if (obj_person.roleType === 9786) {
      obj_person.str_roleType = "管理员"
    } else if (obj_person.roleType === 1) {
      obj_person.str_roleType = "营养师"
    } else if (obj_person.roleType === 3) {
      obj_person.str_roleType = "商家"
    }
    return obj_person;
  },

  //将对象的图片地址增加随机参数,七牛云缓存机制
  /**
   * @param {List} object
   * @deprecated 
   * @version 1.0
   */
  addRandomSuffixData: function (object) {
    object.forEach((item) => {
      if (item.imgUrl == null || item.imgUrl == "") {} else {
        //存在完整地址
        item.imgUrl = `${item.imgUrl}?random=${Date.now()}`;
      }
    });
  },

  removeRandomSuffix_Key: function (object) {
    let firstParamIndex = object.imgUrl.lastIndexOf("/");
    let secondParamIndex = object.imgUrl.lastIndexOf("?");
    object.imgUrl = object.imgUrl.substring(0, secondParamIndex)
    let key = object.imgUrl.substring(firstParamIndex + 1)
    return key
  },

  /**
   * 
   * @param {Object} object 
   * @param {String} propertyName 
   * @description 七牛云移除对应的后缀,并且返回key
   * @returns {String}
   */
  qnRemoveRandomSuffix_key: function (object, propertyName) {
    let firstParamIndex = object[propertyName].lastIndexOf("/");
    let secondParamIndex = object[propertyName].lastIndexOf("?");
    object[propertyName] = object[propertyName].substring(0, secondParamIndex)
    let key = object[propertyName].substring(firstParamIndex + 1)
    return key
  },

  /**
   * 
   * @param {Array} listData 
   * @param {String} propertyName 
   * @description 为每一项数据图片添加随机后缀
   * @returns {Array}
   */
  qnAddRandomSuffixData_list: function (listData, propertyName) {
    listData.forEach(item => {
      if (item[propertyName] == null || item[propertyName] == "") {

      } else {
        item[propertyName] = `${item[propertyName]}?random=${Date.now()}`
      }
    })
    return listData
  },

  /**
   * @param {object} object 
   * @param {string} propertyName 
   * @description 对象的属性是否含有值 有则返回true 无返回false
   */
  propertyHasValue_boolean: function (object, propertyName) {
    if (object[propertyName] === "" || object[propertyName] === null || object[propertyName].length === 0) {
      return false
    } else {
      return true
    }
  },

  /**
   * 
   * @param {object} object_person 
   * @returns 
   * @description 判断是否为管理员 
   */
  isAdmin_boolean(object_person) {
    if (object_person.str_roleType === "管理员") {
      return true;
    }
    return false;
  },

  /**
   * 
   * @param {Object} object 
   * @returns 
   * @description 判断对象是否为空对象 
   */
  isEmptyObject_boolean(object) {
    for (var key in object) {
      return false
    }
    return true
  },

  /**
   * 去除日期中的时分秒
   * @param {*} date：带time的日期格式 
   * @returns 
   */
  formatDate: function (date) {
    return date.substring(0, 11);
  },

  /**
   * 获取某月份的天数
   * @param {*} val 
   */
  getMonthDays: function (year, month) {
    var thisDate = new Date(year, month, 0);  //当天数为0 js自动处理为上一月的最后一天
    return thisDate.getDate();
  }
}
export {
  utils
}